#include "fd_manger.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "hook.h"

namespace sylar
{

FdCtx::FdCtx(int fd) 
    : m_isInit(false)
    , m_isSocket(false)
    , m_isSysNoBlock(false)
    , m_isUserNoBlock(false)
    , m_isClosed(false)
    , m_fd (-1) 
    , m_recvTimeout(0)
    , m_sendTimeout(0)
    , m_iomanger(nullptr)
{
    init();
}

FdCtx::~FdCtx()
{
}

bool FdCtx::init()
{
    if (m_isInit)
    {
        return true;
    }

    m_recvTimeout = -1;
    m_sendTimeout = -1;

    struct stat fd_stat;

    if (-1 == fstat(m_fd, &fd_stat))
    {
        m_isInit = false;
        m_isSocket = false;
    }
    else
    {
        m_isInit = true;
        m_isSocket = S_ISSOCK(fd_stat.st_mode);
    }

    if (m_isSocket)
    {
        int flag = fcntl_f(m_fd, F_GETFD, 0);
        if (! (flag & O_NONBLOCK))
        {
            fcntl_f(m_fd, F_SETFD, flag | O_NONBLOCK);
        }
        m_isSysNoBlock = true;
    }
    else
    {
        m_isSysNoBlock = false;
    }

    m_isUserNoBlock = false;
    m_isClosed = false;
    return m_isInit;
}

void FdCtx::setTimeOut(int type, uint64_t v)
{
}

void FdCtx::getTimeOut(int type)
{
}

FdManger::FdManger()
{
    m_datas.resize(64);
}

FdCtx::ptr FdManger::get(int fd, bool auto_create)
{
    return FdCtx::ptr();
}


}